﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Vds2465Parser
{
	internal static class GenParse_Helper
	{
		#region constants

		private const byte HighBytePlaceHolder = 0x0F;

		#endregion constants

		#region internal methods

		/// <summary>
		/// A number like 12345 is converted into bytes:
		/// [0] 0x21
		/// [1] 0x43
		/// [2] 0xF5
		/// </summary>
		/// <param name="numberString"></param>
		/// <returns></returns>
		internal static byte[] GenerateNumberBytes(string numberString)
		{
			// determine number of bytes
			if (String.IsNullOrEmpty(numberString) == false)
			{
				int nrOfDigits = numberString.Length;
				int nrOfIdNumberBytes = (int)Math.Ceiling(nrOfDigits / 2.0);
				byte[] idNumberBytes = new byte[nrOfIdNumberBytes];

				int targetDigitIndex = 0;
				for (int sourceDigitIndex = 0; sourceDigitIndex < numberString.Length; sourceDigitIndex = sourceDigitIndex + 2)
				{
					byte lowNibble = ConvertASCIINumberByte(numberString[sourceDigitIndex]);
					byte highNibble = HighBytePlaceHolder;
					if (sourceDigitIndex < numberString.Length - 1)
					{
						highNibble = ConvertASCIINumberByte(numberString[sourceDigitIndex + 1]);
					}

					idNumberBytes[targetDigitIndex] = (byte)(highNibble * 16 + lowNibble);
					targetDigitIndex++;
				}

				return idNumberBytes;
			}
			
			// TODO handle error
			
			return null;
		}

		internal static string ParseNumberBytes(byte[] numberBytes)
		{
			if ((numberBytes != null) && (numberBytes.Length > 0))
			{
				StringBuilder stringBuilder = new StringBuilder();
				for (int index = 0; index < numberBytes.Length; index++)
				{
					byte lowNibble = (byte) (numberBytes[index] % 16);
					stringBuilder.Append(lowNibble.ToString());
					
					byte highNibble = (byte)(numberBytes[index] / 16);
					if (highNibble != HighBytePlaceHolder)
					{
						stringBuilder.Append(highNibble.ToString());
					}
				}

				return stringBuilder.ToString();
			}

			// TODO handle error

			return String.Empty;
		}

		#endregion internal methods

		#region private methods

		private static byte ConvertASCIINumberByte(char asciiChar)
		{
			byte asciiByte = (byte) asciiChar;
			return (byte) (asciiByte - 0x30);
		}

		#endregion private methods
	}
}
